package com.yifeng.repo.micro.service.server.engine.core;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * ServletRequest的 getReader() 和 getInputStream() 只能被调用一次，并且不能两个都调用.
 * 自定义HttpServletRequestWrapper达成重复读取流数据的目标
 * Created by daibing on 2023/3/14.
 */
public class JsonRequestWrapper extends HttpServletRequestWrapper {
    private final Map<String , String[]> params = new HashMap<>();
    private final byte[] body;

    public JsonRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        params.putAll(request.getParameterMap());
        body = IOUtils.toByteArray(request.getInputStream());
    }

    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream data = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() throws IOException {
                return data.read();
            }
        };
    }

}
